<template>
  <div class="sidebar">
    <h5 class="animate__animated animate__fadeInLeft">Markdown文件列表</h5>
    
    <!-- 分类选择 -->
    <div class="category-selector mb-3">
      <label class="form-label text-light">选择分类</label>
      <select class="form-select" v-model="localSelectedCategory" @change="onCategoryChange">
        <option v-for="category in categories" :key="category.id" :value="category">
          {{ category.name }}
        </option>
      </select>
    </div>
    
    <!-- 操作按钮 -->
    <div class="action-buttons mb-3">
      <button class="btn btn-light btn-sm me-2" @click="openCreateModal">
        <i class="bi bi-file-earmark-plus"></i> 新建文档
      </button>
      <button class="btn btn-light btn-sm" @click="triggerFileUpload">
        <i class="bi bi-upload"></i> 上传文档
      </button>
      <input 
        type="file" 
        ref="fileInput" 
        @change="handleFileUpload" 
        accept=".md,.markdown,text/markdown"
        style="display: none"
      >
    </div>
    
    <!-- 搜索框 -->
    <div class="search-box">
      <i class="bi bi-search"></i>
      <input type="text" class="form-control" placeholder="搜索文件..." v-model="searchTerm">
    </div>
    
    <!-- 文件列表 -->
    <div v-if="loading" class="text-center py-4 text-light">
      <div class="spinner-border spinner-border-sm" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
      <span class="ms-2">加载中...</span>
    </div>
    
    <p class="section-title" v-if="!loading && filteredFiles.length > 0">文件列表</p>
    <p class="section-title text-warning" v-if="!loading && filteredFiles.length === 0">
      无文件
    </p>
    
    <ul class="file-list animate__animated animate__fadeInUp" v-if="!loading">
      <li 
        v-for="file in filteredFiles" 
        :key="file.name"
        class="file-item" 
        :class="{ active: currentFile === file.name }"
      >
        <div class="file-content" @click="selectFile(file.name)">
          <i class="bi bi-file-earmark-text file-icon"></i>
          <div>
            <div class="file-name">{{ file.name }}</div>
            <div class="file-meta">更新于 {{ formatDate(file.updateTime) }}</div>
          </div>
        </div>
        <button 
          class="btn btn-delete" 
          @click.stop="confirmDelete(file.name)"
          title="删除文件"
        >
          <i class="bi bi-trash"></i>
        </button>
      </li>
    </ul>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteModal" class="custom-modal-overlay" @click="closeDeleteModal">
      <div class="custom-modal" @click.stop>
        <div class="modal-header">
          <h5 class="modal-title">确认删除</h5>
          <button type="button" class="btn-close" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          确定要删除文件 "{{ fileToDelete }}" 吗？此操作不可恢复。
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeDeleteModal">取消</button>
          <button type="button" class="btn btn-danger" @click="deleteFile">删除</button>
        </div>
      </div>
    </div>

    <!-- 新建文档对话框 -->
    <div v-if="showCreateModal" class="custom-modal-overlay" @click="closeCreateModal">
      <div class="custom-modal" @click.stop>
        <div class="modal-header">
          <h5 class="modal-title">新建文档</h5>
          <button type="button" class="btn-close" @click="closeCreateModal">×</button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="newFileName" class="form-label">文件名</label>
            <input 
              type="text" 
              class="form-control" 
              id="newFileName" 
              v-model="newFileName"
              placeholder="请输入文件名（不需要.md后缀）"
            >
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeCreateModal">取消</button>
          <button type="button" class="btn btn-primary" @click="createFile">创建</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 移除Bootstrap Modal依赖，使用Vue原生实现
import api from '../services/api';

export default {
  name: 'FileList',
  props: {
    categories: {
      type: Array,
      default: () => []
    },
    selectedCategory: {
      type: [String, Object],
      default: ''
    },
    files: {
      type: Array,
      required: true
    },
    currentFile: {
      type: String,
      default: null
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchTerm: '',
      localSelectedCategory: this.selectedCategory,
      fileToDelete: null,
      showDeleteModal: false,
      showCreateModal: false,
      newFileName: '',
      uploadLoading: false
    }
  },
  watch: {
    selectedCategory(newVal) {
      this.localSelectedCategory = newVal;
    }
  },
  computed: {
    filteredFiles() {
      if (!this.searchTerm) return this.files;
      
      return this.files.filter(file => 
        file.name.toLowerCase().includes(this.searchTerm.toLowerCase())
      );
    }
  },
  methods: {
    selectFile(fileName) {
      // 添加点击动画效果
      const element = event.currentTarget;
      element.classList.add('animate__animated', 'animate__pulse');
      setTimeout(() => {
        element.classList.remove('animate__animated', 'animate__pulse');
      }, 500);
      
      this.$emit('select-file', fileName);
    },
    onCategoryChange() {
      this.$emit('select-category', this.localSelectedCategory);
    },
    categoryDisplayName(category) {
      // 直接返回分类名称，因为现在category是对象
      return category && category.name ? category.name : '未知分类';
    },
    formatDate(dateString) {
      if (!dateString) return '未知时间';
      
      try {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      } catch (e) {
        return dateString;
      }
    },
    confirmDelete(fileName) {
      this.fileToDelete = fileName;
      this.showDeleteModal = true;
    },
    
    closeDeleteModal() {
      this.showDeleteModal = false;
      this.fileToDelete = null;
    },
    
    async deleteFile() {
      try {
        const filename = this.fileToDelete.replace(/\.md$/, '');
        // 确保传递正确的分类名称
        const categoryName = this.localSelectedCategory?.name || this.localSelectedCategory;
        await api.content.delete(categoryName, filename);
        this.closeDeleteModal();
        this.$emit('file-deleted', this.fileToDelete);
        
        // 显示成功消息
        this.$emit('show-alert', {
          message: `文件 "${this.fileToDelete}" 已成功删除`,
          type: 'success'
        });
        
        // 如果删除的是当前文件，清空编辑器
        if (this.currentFile === this.fileToDelete) {
          this.$emit('select-file', null);
        }
        
        // 重新加载文件列表
        this.$emit('select-category', this.localSelectedCategory);
      } catch (error) {
        this.$emit('show-alert', {
          message: `删除文件失败: ${error.message}`,
          type: 'danger'
        });
      }
    },

    openCreateModal() {
      this.newFileName = '';
      this.showCreateModal = true;
    },
    
    closeCreateModal() {
      this.showCreateModal = false;
      this.newFileName = '';
    },

    async createFile() {
      if (!this.newFileName.trim()) {
        this.$emit('show-alert', {
          message: '请输入文件名',
          type: 'warning'
        });
        return;
      }

      if (!this.localSelectedCategory) {
        this.$emit('show-alert', {
          message: '请先选择分类',
          type: 'warning'
        });
        return;
      }

      try {
        // 获取分类ID
        const categoryId = this.localSelectedCategory?.id;
        
        if (!categoryId) {
          this.$emit('show-alert', {
            message: '分类信息无效，请重新选择分类',
            type: 'warning'
          });
          return;
        }
        
        // 创建新文档，传递分类ID
        const filename = this.newFileName;
        const content = `# ${this.newFileName}\n\n请在此处编写内容...`;
        
        // 调用API创建文档，传递分类ID
        await api.content.create(filename, content, categoryId);
        this.closeCreateModal();
        
        // 显示成功消息
        this.$emit('show-alert', {
          message: `文件 "${this.newFileName}" 已创建`,
          type: 'success'
        });
        
        // 重新加载文件列表
        this.$emit('select-category', this.localSelectedCategory);
        
        // 选择新创建的文件
        this.$emit('select-file', `${this.newFileName}.md`);
      } catch (error) {
        this.$emit('show-alert', {
          message: `创建文件失败: ${error.message}`,
          type: 'danger'
        });
      }
    },

    triggerFileUpload() {
      this.$refs.fileInput.click();
    },

    async handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 检查文件类型
      if (!file.name.toLowerCase().endsWith('.md') && !file.type.includes('markdown')) {
        this.$emit('show-alert', {
          message: '请上传 Markdown 文件（.md）',
          type: 'warning'
        });
        return;
      }

      try {
        this.uploadLoading = true;
        
        // 读取文件内容
        const reader = new FileReader();
        reader.onload = async (e) => {
          try {
            const content = e.target.result;
            const filename = file.name.replace(/\.md$/i, '');
            
            // 获取分类ID
            const categoryId = this.localSelectedCategory?.id;
            
            if (!categoryId) {
              this.$emit('show-alert', {
                message: '分类信息无效，请重新选择分类',
                type: 'warning'
              });
              return;
            }
            
            await api.content.upload(filename, content, categoryId);
            
            // 显示成功消息
            this.$emit('show-alert', {
              message: `文件 "${file.name}" 上传成功`,
              type: 'success'
            });
            
            // 重新加载文件列表
            this.$emit('select-category', this.localSelectedCategory);
            
            // 选择新上传的文件
            this.$emit('select-file', file.name);
          } catch (error) {
            this.$emit('show-alert', {
              message: `上传文件失败: ${error.message}`,
              type: 'danger'
            });
          } finally {
            this.uploadLoading = false;
            // 清空文件输入框，允许重复上传同一个文件
            event.target.value = '';
          }
        };
        
        reader.readAsText(file);
      } catch (error) {
        this.$emit('show-alert', {
          message: `文件格式错误: ${error.message}`,
          type: 'danger'
        });
        this.uploadLoading = false;
        event.target.value = '';
      }
    }
  }
}
</script>

<style scoped>
.sidebar {
  width: 300px;
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: white;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  padding: 20px;
  overflow-y: auto;
  transition: all var(--transition-speed);
}

.sidebar h5 {
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid rgba(255, 255, 255, 0.3);
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.file-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.file-item {
  padding: 12px 15px;
  border-radius: var(--border-radius);
  cursor: pointer;
  margin-bottom: 8px;
  transition: all var(--transition-speed);
  background-color: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-item:hover {
  background-color: rgba(255, 255, 255, 0.2);
  transform: translateX(5px);
}

.file-item.active {
  background-color: rgba(255, 255, 255, 0.3);
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.file-icon {
  margin-right: 10px;
  font-size: 1.2rem;
}

.search-box {
  position: relative;
  margin-bottom: 20px;
}

.search-box input {
  padding-left: 40px;
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  border-radius: var(--border-radius);
}

.search-box input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.search-box input:focus {
  background-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2);
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(255, 255, 255, 0.7);
}

.section-title {
  font-size: 0.9rem;
  text-transform: uppercase;
  letter-spacing: 1px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 15px;
}

.file-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-meta {
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 3px;
}

.category-selector select {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
}

.category-selector select:focus {
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2);
  background-color: rgba(255, 255, 255, 0.3);
}

.category-selector select option {
  background-color: var(--primary-color);
  color: white;
}

.file-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.btn-delete {
  padding: 4px 8px;
  background-color: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.2s;
  opacity: 0;
}

.file-item:hover .btn-delete {
  opacity: 1;
}

.btn-delete:hover {
  color: #ff4444;
  transform: scale(1.1);
}

/* 确保模态框中的文本是深色的 */
.modal-content {
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  transition: all var(--transition-speed);
}

.action-buttons .btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.action-buttons .btn i {
  font-size: 1.1em;
}

/* 自定义模态框样式 */
.custom-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1050;
  animation: fadeIn 0.15s ease-out;
}

.custom-modal {
  background: white;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow: hidden;
  animation: slideIn 0.15s ease-out;
}

.modal-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f8f9fa;
}

.modal-title {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 500;
  color: #333;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-close:hover {
  color: #000;
}

.modal-body {
  padding: 1.5rem;
  color: #333;
}

.modal-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid #dee2e6;
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
  background-color: #f8f9fa;
}

.modal-footer .btn {
  padding: 0.5rem 1rem;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: all 0.15s ease-in-out;
}

.modal-footer .btn-secondary {
  background-color: #6c757d;
  border-color: #6c757d;
  color: white;
}

.modal-footer .btn-secondary:hover {
  background-color: #5a6268;
  border-color: #545b62;
}

.modal-footer .btn-danger {
  background-color: #dc3545;
  border-color: #dc3545;
  color: white;
}

.modal-footer .btn-danger:hover {
  background-color: #c82333;
  border-color: #bd2130;
}

.modal-footer .btn-primary {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

.modal-footer .btn-primary:hover {
  background-color: #0069d9;
  border-color: #0062cc;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-50px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>